package lingnan.controller;

import lingnan.entity.User;
import lingnan.service.BookConsumerService;
import lingnan.service.UserConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("user")
public class UserConsumerController {
    @Autowired
    private UserConsumerService userConsumerService;

    @Autowired
    private BookConsumerService bookConsumerService;
//    @PostMapping("queryAll")
//    public Object queryAll(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit, @RequestBody User bean){
//        return userConsumerService.queryAll(page,limit,bean);
//    }
//
//    @PostMapping("save")
//    public Object save(@RequestBody User bean){
//        return userConsumerService.save(bean);
//    }
//    @PostMapping("delete")
//    public Object delete(@RequestBody Integer[] ids){
//        return userConsumerService.delete(ids);
//    }

    @GetMapping(value="/getMapJson")
    @ResponseBody
    public Map<String, Object> getMapJson(){
        return userConsumerService.getMapJson();
    }

    @PostMapping("/findJson")
    @ResponseBody
    Map<String, Object> findJson(String value,String domain){
        return userConsumerService.findJson(value,domain);
    }
    //json执行删除操作
    @PostMapping("/deleteJson")
    @ResponseBody
    public String deleteJson(Integer id) {
        return userConsumerService.deleteJson(id);
    }

    @RequestMapping(value="/updateGo")
    public String updateGo(Integer id, Model model){
        User bean = userConsumerService.getById(id);
        model.addAttribute("bean",bean);
        return "manage/manageuserupdate";
    }
    //更新
    @PostMapping("/updateJson")
    @ResponseBody
    public boolean update(User bean) {
        System.out.println(bean);
        return userConsumerService.updatejson(bean);
    }
    @RequestMapping("test")
    public String toTest(){
        return "user/test";
    }

    @RequestMapping("toWelcome")
    public String toWelcome() {
        return "index";
    }

    @RequestMapping("toReg")
    public String toReg() {
        return "reg";
    }

    @RequestMapping("toLogin")
    public String toLogin() {
        return "login";
    }

    @PostMapping("login")
    public String login(String name,
                        String password,
                        @RequestParam(required = false) String isMemory,
                        Model model,
                        HttpSession session,
                        HttpServletRequest request,
                        HttpServletResponse response){
        User bean = userConsumerService.login(name, password, isMemory);
        if( bean != null ) {
            //是否记住密码
            isMe(bean, isMemory, request, response);
            //session保存
            session.setAttribute("loginUser", bean);
            //根据权限进入页面
            if(bean.getAccess() == 0){
                //管理界面
                return "manage/manage";
            } else {
                //主页
                return "index";
            }
        }else{
            //登录失败
            model.addAttribute("loginError", "账号或密码错误");
            return "login";
        }
    }

    @RequestMapping("loginOut")
    public String loginOut(HttpSession session) {
        System.out.println("消费者：退出登录!");
        session.removeAttribute("loginUser");
        return "login";
    }

    @PostMapping("reg")
    public String reg(@Valid User bean,
                      BindingResult br,
                      String cfmPassword,
                      Model model,
                      ModelMap modelMap){
        System.out.println("new user:::" + bean);
        //表单数据验证
        if(br.hasErrors()) {
            Map<String, String> errors = new HashMap<String, String>();
            System.out.println("==============================表单数据错误=================================");
            List<FieldError> fieldErrors = br.getFieldErrors();
            for (FieldError item : fieldErrors) {
                System.out.println(item.getField()+":");
                System.out.println(item.getDefaultMessage());
                errors.put(item.getField(), item.getDefaultMessage());
            }
            model.addAttribute("errors", errors);
            return "reg";
        }
        //其他数据验证
        String result = userConsumerService.reg(bean, cfmPassword);
        if( !result.equals("msgRegSuccess") ){
            switch (result) {
                case "msgCfmPasswordError":
                    model.addAttribute("msgCfmPasswordError", "两次输入密码不一致!");
                    break;
                case "msgNameUsedError":
                    model.addAttribute("msgNameUsedError", "该用户名已经被使用!");
                    break;
                default:
                    model.addAttribute("msgIsSuccess", false);
                    model.addAttribute("msgRegFailed", "注册失败!");
                    break;
            }
            return "reg";
        }

        //注册成功
        model.addAttribute("msgIsSuccess", true);
        System.out.println("注册成功!");
        return "login";
    }

    @PostMapping("update")
    public String updateUser(User bean,
                             String cfmPassword,
                             String oldPassword,
                             String checkPhone,
                             Model model,
                             HttpSession session){
        //消费者：
        System.out.println("消费者：");
        //获取当前登录用户的id，并且传给bean中的id
        User user = (User) session.getAttribute("loginUser");
        System.out.println("loginUser:::" + user);
        Integer uid = user.getId();
        bean.setId(uid);
        System.out.println("bean:::" + bean);
        System.out.println("cfmPassword:::" + cfmPassword);
        System.out.println("oldPassword:::" + oldPassword);
        System.out.println("checkPhone:::" + checkPhone);
        //调用更新
        String result = userConsumerService.update(bean, cfmPassword, oldPassword, checkPhone);
        if( !result.equals("success")){
            switch (result) {
                case "msgNameUsedError":
                    model.addAttribute("msg", "该用户名已经被使用!");
                    break;
                case "msgOldPassError":
                    model.addAttribute("msg", "原密码错误！请重试!");
                    break;
                case "msgTwoPassError":
                    model.addAttribute("msg", "两次输入密码不一致!");
                    break;
                case "msgPhoneError":
                    model.addAttribute("msg", "手机验证错误！请重试!");
                    break;
                default:
//                    model.addAttribute("msg", false);
                    model.addAttribute("msg", "更新失败!请重试！");
                    break;
            }
            return "user/user";
        }else {
            //当前登录的账户信息改变
            User newBean = userConsumerService.getById(uid);
            System.out.println("更新后的用户信息:::" + newBean);
            session.setAttribute("loginUser", newBean);
            //如果进行了修改密码，要重新登录
            if(oldPassword != null){
                return loginOut(session);
            }else {
                //更新成功且无需重新登录的情况：result.equals("success")
                return "user/user";
            }
        }
    }

    @GetMapping("getById")
    @ResponseBody
    public Object getById(Integer id ){
        return userConsumerService.getById(id);
    }

    @RequestMapping(value="/mine")
    public String mine(HttpSession session){
        User user=(User) session.getAttribute("loginUser");
        int id=user.getId();
        int userId=user.getId();
        System.out.println("id:::"+id);
        session.setAttribute("allBook", bookConsumerService.getBookAllByUser(userId));
        session.setAttribute("checking", bookConsumerService.getBookAllByStateUser(1,id));
        session.setAttribute("outDate", bookConsumerService.getBookAllByStateUser(0,id));
        session.setAttribute("confirm", bookConsumerService.getBookAllByStateUser(2,id));
        System.out.println("allBook:::"+bookConsumerService.getBookAllByUser(userId));
        System.out.println("checking:::"+bookConsumerService.getBookAllByStateUser(1,id));
        System.out.println("outDate:::"+bookConsumerService.getBookAllByStateUser(0,id));
        System.out.println("confirm:::"+bookConsumerService.getBookAllByStateUser(2,id));
        return "user/user";
    }

    /**
     * 实使用cookie保存用户名（账号）和密码
     *
     * @param bean 用户对象
     * @param isMemory 是否记住密码
     * @param request request
     * @param response response
     */
    private void isMe(User bean,@RequestParam(required = false) String isMemory,
                      HttpServletRequest request, HttpServletResponse response) {
        //是否记住密码
        if (isMemory != null && isMemory.equals("on")) {
            Cookie userName = new Cookie("userName", bean.getName());
            Cookie userPassword = new Cookie("userPassword", bean.getPassword());
            Cookie memoryCheck = new Cookie("memoryCheck", "on");
            response.addCookie(userName);
            response.addCookie(userPassword);
            response.addCookie(memoryCheck);
        } else {
            //清除cookie
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }

        }
    }



}